package cn.sh.yhk.acl;

import cn.sh.yhk.acl.filter.JWTAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Classname Yhk
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/10/2 16:52
 * @Created by y6522
 */
@Configuration
public class SecurityConfig {

    @Autowired
    private JWTAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    private UserLogoutHandler userLogoutHandler;

    /**
     * 密码明文加密方式配置
     * 默认加密方式
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 获取AuthenticationManager（认证管理器），登录时认证使用
     * 默认认证
     *
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().requestMatchers("/WebSocket/**");
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(it -> it.disable())

                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))//禁用session，前后端分离不需要
                .httpBasic(httpBasic -> httpBasic.disable())//
                .authorizeHttpRequests(
                        auth -> auth.requestMatchers(
                                        //茅台小程序
                                        "/maotai/**", "/file/**",
                                        //后台管理
                                        "/register", "/login",
                                        "/webSocket/**"
                                ).permitAll()
                                .anyRequest().authenticated()
                )//设置权限，除了登录登出不需要认证，其余均需要认证
                .logout(logout -> logout.logoutUrl("/logout").addLogoutHandler(userLogoutHandler))
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)//添加JWT的处理过滤器，用于从JWT中解析																												用户信息
                //TODO 精确到按钮 不想写了 ==>perrmission控制菜单下的非menu链接
//                .addFilterAfter()
                .csrf(AbstractHttpConfigurer::disable)
                .exceptionHandling(e -> e.authenticationEntryPoint(myAuthenticationEntryPoint))//自定义用户认证失败的处理器，否则的话，当用户未认证的情况下，浏览器会直接报出403异常，我们需要的是json提示信息，供前端处理，设置前后效果如下图所示
                .exceptionHandling(e -> e.accessDeniedHandler(myAccessDeniedHandler))
                .build();
    }


}
